package com.mti.monitor.service;

import com.mti.monitor.bean.model.DbTable;
import com.mti.monitor.bean.model.DbTableColumn;
import com.mti.monitor.bean.model.MonitorPage;
import com.mti.monitor.bean.model.SysDataSourceConfig;
import com.mti.monitor.config.DataSourceContextHolder;
import com.mti.monitor.config.DynamicDataSource;
import com.mti.monitor.mapper.SysDataSourceConfigMapper;
import com.mti.monitor.mapper.SysMonitorConfigMapper;
import com.mti.monitor.util.AESUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;


@Service
@Log4j2
public class SysDataSourceConfigService {

    @Autowired
    private SysDataSourceConfigMapper sysDataSourceConfigMapper;

    @Autowired
    private SysMonitorConfigMapper sysMonitorConfigMapper;

    @Autowired
    private DynamicDataSource dynamicDataSource;


    public List<SysDataSourceConfig> selectAll() {
        return sysDataSourceConfigMapper.selectAllList();
    }

    public List<DbTable> selectDbTableList(String dataSourceId) {
        try {
            SysDataSourceConfig dataSource = sysDataSourceConfigMapper.selectById(dataSourceId);
            //创建数据源连接&检查 若存在则不需重新创建
            dynamicDataSource.createDataSourceWithCheck(dataSource);
            //切换到该数据源
            DataSourceContextHolder.setDataSourceType(dataSource.getDataSourceId());
            List<DbTable> list = sysDataSourceConfigMapper.selectDbTableList();
            DataSourceContextHolder.clearDataSourceType();
            return list;
        }catch (Exception e){
            throw new IllegalArgumentException("数据源异常");
        }
    }

    public List<DbTableColumn> selectDbTableColumnList(String dataSourceId, String tableName) {
        try {
            SysDataSourceConfig dataSource = sysDataSourceConfigMapper.selectById(dataSourceId);
            //创建数据源连接&检查 若存在则不需重新创建
            dynamicDataSource.createDataSourceWithCheck(dataSource);
            //切换到该数据源
            DataSourceContextHolder.setDataSourceType(dataSource.getDataSourceId());
            List<DbTableColumn> list = sysDataSourceConfigMapper.selectDbTableColumnList(tableName);;
            DataSourceContextHolder.clearDataSourceType();
            return list;
        }catch (Exception e){
            throw new IllegalArgumentException("数据源异常");
        }
    }

    public MonitorPage selectPage(MonitorPage page) {
        int total = sysDataSourceConfigMapper.selectCount();
        List list = sysDataSourceConfigMapper.selectPage((page.getStart() - 1) * page.getSize(), page.getSize());
        page.setTotal(total);
        page.setList(list);
        return page;
    }

    public SysDataSourceConfig selectById(String id){
        return sysDataSourceConfigMapper.selectById(id);
    }

    public void create(SysDataSourceConfig sysDataSourceConfig) {
        //先测试数据源是否可用
        if(dynamicDataSource.testDatasource(null, sysDataSourceConfig.getDriveClassName()
                , sysDataSourceConfig.getDbUrl(), sysDataSourceConfig.getUserName()
                , sysDataSourceConfig.getPassword())) {

            sysDataSourceConfig.setDataSourceId(UUID.randomUUID().toString().replaceAll("-", ""));
            sysDataSourceConfig.setDeleteYn(false);
            sysDataSourceConfig.setCreateTime(new Date());
            String pwd = AESUtil.encode(AESUtil.DEFAULT_SECRET_KEY, sysDataSourceConfig.getPassword());
            sysDataSourceConfig.setPassword(pwd);
            sysDataSourceConfigMapper.insert(sysDataSourceConfig);
        }else{
            //数据源不可用
            log.error("创建数据源失败，该数据源不可用");
            throw new IllegalArgumentException("该数据源不可用");
        }
    }

    public void update(SysDataSourceConfig sysDataSourceConfig) {
        if(dynamicDataSource.testDatasource(null, sysDataSourceConfig.getDriveClassName()
                , sysDataSourceConfig.getDbUrl(), sysDataSourceConfig.getUserName()
                , sysDataSourceConfig.getPassword())) {
            String pwd = AESUtil.encode(AESUtil.DEFAULT_SECRET_KEY, sysDataSourceConfig.getPassword());
            sysDataSourceConfig.setPassword(pwd);
            sysDataSourceConfigMapper.updateById(sysDataSourceConfig);
        }else{
            //数据源不可用
            log.error("创建数据源失败，该数据源不可用");
            throw new IllegalArgumentException("该数据源不可用");
        }

    }


    public void delete(String id) {
        boolean isExist = sysMonitorConfigMapper.checkExist(id) == 0;
        if (isExist) {
            SysDataSourceConfig sysDataSourceConfig = new SysDataSourceConfig();
            sysDataSourceConfig.setDeleteYn(true);
            sysDataSourceConfig.setDataSourceId(id);
            sysDataSourceConfigMapper.updateById(sysDataSourceConfig);
        } else {
            log.error("该数据源已被使用，不允许删除");
            throw new IllegalArgumentException("该数据源已被使用，不允许删除");
        }
    }

}
